import router from "./router";
import { ElMessage } from "element-plus";
import useStore from "@/store";

// npm i --save-dev @types/nprogress
// npm install --save nprogress
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度环显示/隐藏

// 白名单路由
const whiteList = ["/login"];
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const { user, permission } = useStore();
  const hasToken = localStorage.getItem("token");
  if (hasToken) {
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      // 是否有匹配到的路由信息
      if(user.routes.length>0){
        if (to.matched.length === 0) {
          from.name ? next({ name: from.name as any }) : next("/401");
        }else{
          next()
        }
      }else{
        const routes = await user.getMenuList();
        routes.forEach((route: any) => {
          router.addRoute(route);
        });
        next({ ...to, replace: true });
      }
      // if (to.matched.length === 0) {
      //   from.name ? next({ name: from.name as any }) : next("/401");
      // } else {
      //   if(user.routes.length<=0){
          
      //   }
      // }
      // else {
      //   from.name ? next({ name: from.name as any }) : next("/401");
      // }
      // try {
      //   // await user.getUserInfo()
      //   // const accessRoutes:any = await permission.generateRoutes(user.roles)
      //   // accessRoutes.forEach((route: any) => {
      //   //   router.addRoute(route);
      //   // });
      //   // console.log(accessRoutes);

      //   // console.log(router.getRoutes(),'fdfdfdfdf');

      //   next({ ...to, replace: true });
      // } catch (error) {
      //   // 移除 token 并跳转登录页
      //   // await user.resetToken();
      //   // ElMessage.error((error as any) || 'Has Error');
      //   // next(`/login?redirect=${to.path}`);
      //   // NProgress.done();
      // }
    }
  } else {
    // 白名单
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: "/login"});
      NProgress.done();
    }
  }
  // next();
});

router.afterEach((to:any) => {
  if(to.name){
    document.title = to.name
  }
  NProgress.done();
});
